package com.chz.SupermarketMS.controllers;

import com.chz.SupermarketMS.dao.UserAccountRepository;
import com.chz.SupermarketMS.entities.UserAccount;
import com.chz.SupermarketMS.service.UserAccountService;
import jdk.jfr.Registered;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class SecurityController {
    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    UserAccountService userAccountService;

    @GetMapping("/register")
    public String register(Model model){

        UserAccount userAccount = new UserAccount();
        model.addAttribute("userAccount",userAccount);

        return "security/register";
    }

    @GetMapping("login")
    public String login(){
        return "security/login";
    }

    @GetMapping("logout")
    public String logout(){
        return "security/logout";
    }



    @PostMapping("register/save")
    public String saveUser(Model model,UserAccount userAccount){

        userAccount.setPassword(bCryptPasswordEncoder.encode(userAccount.getPassword()));
        userAccount.setRole("ROLE_USER");
        userAccountService.save(userAccount);

        return "redirect:/login";
    }

}
